//
//  BaseService.m
//  CqlivingCloud
//
//  Created by xinhualong on 16/4/22.
//  Copyright © 2016 xinhualong. All rights reserved.
//

#import "BaseService.h"
#import "BaseViewController.h"
#import "UUID.h"
#import <sys/utsname.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/AdSupport.h>
#import "LoginViewController.h"
#import <CoreTelephony/CTTelephonyNetworkInfo.h>

@interface BaseService()


@property (assign, nonatomic) BOOL isAlertShow;
/**

 */
@property (strong, nonatomic) AFHTTPSessionManager *session;

/**
 */
@property (assign, nonatomic) BOOL isLoadingUserVisit;

@end

@implementation BaseService

+ (instancetype)sharedInstance {
    static BaseService *instance = nil;
    static dispatch_once_t once = 0;
    dispatch_once(&once, ^{
        instance = [[BaseService alloc] init];
        instance.isLoadingUserVisit = false;
        NSString *urr = BaseUrl;
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        if(!CHStringIsEmpty([defaults objectForKey:@"netUrlAddress"])){
            urr = [defaults objectForKey:@"netUrlAddress"];
        }
        instance.session = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:urr]];
        instance.session.requestSerializer.timeoutInterval = RequestTimeoutInterval;
        instance.session.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
        instance.requestBaseUrl = urr;
    });
    return instance;
}

+ (BOOL)networkEnable {
    
    AFNetworkReachabilityManager *reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    __block BOOL isNet = YES;
    [reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                isNet = YES;
                
                break;
            case AFNetworkReachabilityStatusNotReachable:
                
                isNet = NO;
                break;
            default:
                break;
        }
    }];
    
    [reachabilityManager startMonitoring];
    return isNet;
    
}

+ (NSString *)getRequestUrlString:(NSString *)str {
    
    NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    
    NSString *url= [NSString stringWithFormat:@"%@%@?areal=%@&boo=%@&howling=%@&ear=%@&knew=%@&minute=%@&which=1",[BaseService sharedInstance].requestBaseUrl,str,[UserInfoModel getUserInfo].areal,appVersion,[BaseService friendlyDeviceName],[UUID getUUID],[[UIDevice currentDevice] systemVersion],[BaseService getIDFA]];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    return url;
}

+ (AFHTTPSessionManager *)getSessionManager {
    
    AFHTTPSessionManager *returnSession = [BaseService sharedInstance].session;
    return returnSession;
}

#pragma mark -
//get
+ (void)requestForHttpGet:(NSString *)urlString
               parameters:(NSDictionary *)par
                  success:(SuccessBlock)successBlock
                  failure:(FailureBlock)failereBlock {
    
    NSLog(@"request url------%@\t params---------------%@",[self getRequestUrlString:urlString],par);
    
    NSString *url = [self getRequestUrlString:urlString];
    
    
    [[BaseService getSessionManager] GET:url parameters:par headers:@{} progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"request success----url：%@-----------%@",urlString,responseObject);
        NSDictionary *dic = responseObject;
        NSInteger ofexcitement =[[dic objectForKey:@"ofexcitement"] integerValue];
        if(ofexcitement == 0){
            if (successBlock) {
                successBlock(task,responseObject);
            }
        }else if(ofexcitement == -2){
            [BaseService showAlertWithMessage:[dic objectForKey:@"shared"]];
        }else{
            if (failereBlock) {
                failereBlock(task,[[NSError alloc] init]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failereBlock) {
            failereBlock(task,error);
        }
        NSLog(@"request error-----url：%@----------%@",urlString,error);
        
    }];
}

// post
+ (void)requestForHttpPost:(NSString *)urlString
                parameters:(NSDictionary *)par
                   success:(SuccessBlock)successBlock
                   failure:(FailureBlock)failereBlock {
    NSLog(@"request url------%@/t params---------------%@",[self getRequestUrlString:urlString],par);
    
    
    [[BaseService getSessionManager] POST:[self getRequestUrlString:urlString] parameters:par headers:@{} progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"request success----url：%@-----------%@",urlString,responseObject);
        NSDictionary *dic = responseObject;
        NSInteger ofexcitement =[[dic objectForKey:@"ofexcitement"] integerValue];
        if(ofexcitement == -2){
            [BaseService showAlertWithMessage:[dic objectForKey:@"shared"]];
        }else{
            if (successBlock) {
                successBlock(task,responseObject);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failereBlock) {
            failereBlock(task,error);
        }
        NSLog(@"request error-----url：%@----------%@",urlString,error);
    }];
}
+ (void)showAlertWithMessage:(NSString *)message{
    
    if(message.length == 0){
        message = @"Your account login has expired or you have logged in elsewhere, please log in again";
    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Warm reminder"
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *s = [UIAlertAction actionWithTitle:@"Sign in now"
                                                style:UIAlertActionStyleDefault
                                              handler:^(UIAlertAction * _Nonnull action) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        [[UIView xhl_getTopViewController].navigationController pushViewController:vc animated:YES];
    }];
    [alert addAction:s];
    
    UIAlertAction *c = [UIAlertAction actionWithTitle:@"cancel"
                                                style:UIAlertActionStyleCancel
                                              handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:c];
    
    
    [[UIView xhl_getTopViewController] presentViewController:alert animated:YES completion:nil];
    
}

//upload pictures
+ (void)postImageWithUrlString:(NSString *)urlString
                    parameters:(NSDictionary *)par
                     imageData:(NSData *)data
                      progress:(ProgressBlock)progressBlock
                       success:(SuccessBlock)successBlock
                       failure:(FailureBlock)failureBlock {


    NSLog(@"request url------%@/t params---------------%@----",[self getRequestUrlString:urlString],par);
    
    [[BaseService getSessionManager] POST:[self getRequestUrlString:urlString] parameters:par headers:@{}  constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (data) {
            [formData appendPartWithFileData:data name:@"maneton" fileName:@"maneton1.png" mimeType:@"png/jpg"];
            
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progressBlock) {
            progressBlock(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (successBlock) {
            successBlock(task,responseObject);
        }
        NSLog(@"request success----url：%@-----------%@",urlString,responseObject);
   
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failureBlock) {
            failureBlock(task,error);
        }
        NSLog(@"request error-----url：%@----------%@",urlString,error);
       
    }];

}

+ (void)requestForDownloadTask:(NSString *)urlString {
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
     
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
    
        return [NSURL URLWithString:@""];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
     
    }];
    [downloadTask resume];
}

+ (NSString *)getTimeStringSince1970 {
    
    //获取的是自1970年以来的毫秒数
    double timeInterval = [[NSDate date] timeIntervalSince1970];
    long long timeInt = [[NSNumber numberWithDouble:timeInterval] longLongValue];
    return [NSString stringWithFormat:@"%lld",timeInt];
}

#pragma mark -

+ (NSString *)friendlyDeviceName {
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *machine = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    // iPhone 设备
    if ([machine isEqualToString:@"iPhone10,3"]) return @"iPhone X";
    if ([machine isEqualToString:@"iPhone11,8"]) return @"iPhone XR";
    if ([machine isEqualToString:@"iPhone12,1"]) return @"iPhone 12 mini";
    if ([machine isEqualToString:@"iPhone12,3"]) return @"iPhone 12";
    if ([machine isEqualToString:@"iPhone12,5"]) return @"iPhone 12 Pro";
    if ([machine isEqualToString:@"iPhone12,8"]) return @"iPhone 12 Pro Max";
    if ([machine isEqualToString:@"iPhone13,1"]) return @"iPhone 13 mini";
    if ([machine isEqualToString:@"iPhone13,2"]) return @"iPhone 13";
    if ([machine isEqualToString:@"iPhone13,3"]) return @"iPhone 13 Pro";
    if ([machine isEqualToString:@"iPhone13,4"]) return @"iPhone 13 Pro Max";
    if ([machine isEqualToString:@"iPhone14,2"]) return @"iPhone 14";
    if ([machine isEqualToString:@"iPhone14,3"]) return @"iPhone 14 Pro";
    if ([machine isEqualToString:@"iPhone14,4"]) return @"iPhone 14 Plus";
    if ([machine isEqualToString:@"iPhone14,5"]) return @"iPhone 14 Pro Max";
    if ([machine isEqualToString:@"iPhone15,2"]) return @"iPhone 15";
    if ([machine isEqualToString:@"iPhone15,3"]) return @"iPhone 15 Plus";
    if ([machine isEqualToString:@"iPhone15,4"]) return @"iPhone 15 Pro";
    if ([machine isEqualToString:@"iPhone15,5"]) return @"iPhone 15 Pro Max";
    if ([machine isEqualToString:@"iPhone16,2"]) return @"iPhone 16";
    if ([machine isEqualToString:@"iPhone16,3"]) return @"iPhone 16 Plus";
    if ([machine isEqualToString:@"iPhone16,4"]) return @"iPhone 16 Pro";
    if ([machine isEqualToString:@"iPhone16,5"]) return @"iPhone 16 Pro Max";
    if ([machine isEqualToString:@"iPhone17,2"]) return @"iPhone 17";
    if ([machine isEqualToString:@"iPhone17,3"]) return @"iPhone 17 Plus";
    if ([machine isEqualToString:@"iPhone17,4"]) return @"iPhone 17 Pro";
    if ([machine isEqualToString:@"iPhone17,5"]) return @"iPhone 17 Pro Max";
    
    return machine;
}
+ (NSString *)getIDFA {
    __block NSString *idfa = @"";
    [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
        if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
            idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
        }
    }];
    return idfa;
}
+(BOOL)isSimulator{
    NSString *deviceModel = [[UIDevice currentDevice] model];
    if ([deviceModel isEqualToString:@"iPhone Simulator"] ||
        [deviceModel isEqualToString:@"iPad Simulator"]) {
        return YES;
    }
    return NO;
}
+ (NSString *)checkNetworkPermission {
   
    NSString  *network = @"";
    if(!CHStringIsEmpty([JKMVKeyChainUUID getPhoneConnectWifiAddress])){
        network = @"WIFI";
    }else{
        network =  [JKMVKeyChainUUID getNetType];
    }
    return network;
}

@end

